<?php
namespace App\Services\Member;
use App\Models\Users;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;

class MemberService
{
	public function register($request,$SmsCacheContracts)
	{
		if(!$code = $SmsCacheContracts->getVerificationCodes($request->input('verification_key')) ){
			return ['code'=>0,'msg'=>'验证码过期了，请重新获取'];
		}

		if(!hash_equals(strval($code['code']),$request->input('verification_code'))){
			return ['code'=>0,'msg'=>'验证码输入错误请重新输入'];
		}

		// 校验是否重复注册
		if(Users::FindMemberFirst($request->input())){
			return ['code'=>0,'msg'=>'请勿重复注册相同账号'];
		}

		$add_data = [
            'password'=>Hash::make($request->input('password')),
            'name'=>$request->input('name'),
            'phone'=>$request->input('phone')
        ];

        $res = Users::create($add_data);

		//删除 key 的缓存
		$SmsCacheContracts->delVerificationCodes($request->input('verification_key'));
		return $res;
	}

	public function login($request)
	{
		$userInfo = $request->only(['name','password']);

        if (!$user = Users::where('name',$userInfo['name'])->first()){
            return [
                'code' => 422,
                'error' => app('config')->get('error.member.ErrUserExist')
            ];
        }
        // Class '\\App\\Models\\User' not found
        $token = auth('api')->attempt($userInfo);
        if (!$token){
            return [
                'code' => 422,
                'error' => app('config')->get('error.member.ErrUserLogin')
            ];
        }

        $key = "shop::user::".$user['id'];

        Redis::set($key,$token);

        return ['code' => 200,'info' => '登录成功','token' => $token];
	}

	public function getTokenUser()
    {
        // JWTAuth::parseToken()->touser() 上下效果相同
    	$user = JWTAuth::parseToken()->authenticate();
    	return $user;
    }


}